#include "../include/Configuration.hpp"
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <fstream>
#include <sstream>

namespace jpx
{
Configuration::Configuration()
{
    set_string("server.host", "0.0.0.0");
    set_int("server.port", 8080);
    set_int("server.thread_pool_size", 10);
    set_int("server.max_connections", 100);
    set_string("server.log_level", "INFO");
}
Configuration & Configuration::get_Instance()
{
    static Configuration instance;
    return instance;
}
bool Configuration::load_from_file(const string & filename)
{
    lock_guard<mutex> lock(_mutex);

    ifstream file(filename);
    if(!file.is_open())
    {
        cerr << "无法打开配置文件: " << filename << endl;
        return false;
    }
    string line;
    string currentSection;
    while(getline(file, line))
    {
        parse_Ini_line(line, currentSection);
    }
    file.close();
    cout << "从文件加载配置：" << filename << endl;
    return true;
}
string trim(const string & str)
{
    if(str.empty()) return str;
    size_t start = str.find_first_not_of(" \t");
    size_t end = str.find_last_not_of(" \t");
    //如果字符串全是空白字符
    if(start == string::npos)
    {
        return "";
    }
    return str.substr(start, end - start + 1);
}
void Configuration::parse_Ini_line(const string & line, string & currentSection)
{
    //使用安全的修剪函数
    string trimmed = trim(line);
    //跳过空行和注释
    if(trimmed.empty() || trimmed[0] == ';' || trimmed[0] == '#')
    {
        return;
    }
    //处理章节
    if(trimmed[0] == '[' && trimmed[trimmed.size() -1] == ']')
    {
        currentSection = trimmed.substr(1, trimmed.size() - 2);
        currentSection = trim(currentSection);//修剪章节名
        return;
    }
    //处理键值对
    size_t pos = trimmed.find('=');
    if(pos != string::npos && pos > 0 && pos < trimmed.length() - 1)
    {
        string key = trimmed.substr(0, pos);
        string value = trimmed.substr(pos + 1);

        //安全的修剪键值对
        key = trim(key);
        value = trim(value);

        //确保键值对不为空
        if(!key.empty())
        {
            //构建完整键名（包含章节）
            string fullkey = currentSection.empty() ? key : currentSection + "." + key;
            _configMap[fullkey] = value;
        }
    }
        else
        {
            //如果不是有效的键值对格式，记录警告
            cerr << "警告：忽略无效的配置行：'" << trimmed << "'" << endl;
        }
}
void Configuration::load_from_commandLine(int argc, char * argv[])
{
    lock_guard<mutex> lock(_mutex);

    for(int i = 1; i < argc; ++i)
    {
        string arg = argv[i];
        parse_command_line_arg(arg);
    }
    cout << "从命令行加载配置,参数数量：" << argc - 1 << endl;
}
void Configuration::parse_command_line_arg(const string & arg)
{
    if(arg.find("--") == 0)
    {
        size_t pos = arg.find('=');
        if(pos != string::npos)
        {
            string key = arg.substr(2, pos - 2);
            string value = arg.substr(pos + 1);
            _configMap[key] = value;
        }
    }
}
string Configuration::get_string(const string & key, const string & defaultValue) const
{
   lock_guard<mutex> lock(_mutex);
   auto it = _configMap.find(key);
   return (it != _configMap.end()) ? it->second : defaultValue;
}
int Configuration::get_int(const string & key, int defaultValue) const
{
    lock_guard<mutex> lock(_mutex);
    auto it = _configMap.find(key);
    if(it != _configMap.end())
    {
        try{
            return std::stoi(it->second);
        }catch (const exception & e)
        {
            cerr << "配置值转换失败：" << key << "=" << it->second << endl;
        }
    }
    return defaultValue;
}
bool Configuration::get_bool(const string & key, bool defaultValue) const
{
    lock_guard<mutex> lock(_mutex);
    auto it = _configMap.find(key);
    if(it != _configMap.end())
    {
        string value = it->second;
        transform(value.begin(), value.end(), value.begin(), ::tolower);
        return (value == "true" || value == "1" || value == "yes" || value == "on");
    }
    return defaultValue;
}
void Configuration::set_string(const string & key, const string & value)
{
    lock_guard<mutex> lock(_mutex);
    _configMap[key] = value;
}
void Configuration::set_int(const string & key, int value)
{
    lock_guard<mutex> lock(_mutex);
    _configMap[key] = value;
}
void Configuration::set_bool(const string & key, bool value)
{
    lock_guard<mutex> lock(_mutex);
    _configMap[key] = value;
}
void Configuration::display() const
{
    lock_guard<mutex> lock(_mutex);

    cout << "\n=== 服务器配置 ===" << endl;
    for(const auto & pair : _configMap)
    {
        string value = pair.second;
        if(pair.first.find("password") != string::npos)
        {
            value = "******";
        }
        cout << pair.first << " = " << value << endl;
    }
    cout << "=============\n" << endl;
}
}//end of namespace jpx
